#include "DynArray.h"


//	default size of the array is set to 4
template <class T> DynArray<T>::DynArray()
{
	nData = 0;
	arraySize = 4;
	data = new T[arraySize];
}

template <class T> DynArray<T>::DynArray(int a)
{
	nData = 0;
	arraySize = a;
	data = new T[arraySize];
}

template <class T> DynArray<T>::~DynArray()
{
	nData = 0;
	arraySize = 0;
	delete []data;
}

//	if the array is full, double its size
template <class T> bool DynArray<T>::append(T item)
{
	if (nData == arraySize)
	{
		arraySize *= 2;
		T* temp = new T[arraySize];
		if (!temp)
			return false;
		for (int i = 0; i < nData; i++)
			temp[i] = data[i];
		delete []data;
		data = temp;
	}
	data[nData++] = item;
	return true;
}

//	truncate unused memory
template <class T> bool DynArray<T>::truncate()
{
	if (nData < arraySize)
	{
		arraySize = nData;
		T* temp = new T[arraySize];
		if (!temp)
			return false;
		for (int i = 0; i < arraySize; i++)
			temp[i] = data[i];
		delete []data;
		data = temp;
	}
	return true;
}

template <class T> void DynArray<T>::clear()
{
	nData = 0;
}

template <class T> int DynArray<T>::length() const
{
	return nData;
}

template <class T> bool DynArray<T>::empty() const
{
	return nData == 0;
}

template <class T> const T& DynArray<T>::operator[](int index) const
{
	return data[index];
}

template <class T> T& DynArray<T>::operator[](int index)
{
	return data[index];
}